package com.ruoyi.onlinevideo.controller;/**
 * @InterfaceName: VideoController
 * @Description:
 * @Author: YourName
 * @Date: 2023-04-03
 */

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.RandomUtil;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.annotation.InnerAuth;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.onlinevideo.domain.Meeting;
import com.ruoyi.onlinevideo.mapper.MeetingMapper;
import com.ruoyi.onlinevideo.service.MeetingService;
import com.ruoyi.onlinevideo.util.WebsocketConstants;
import com.tencentyun.TLSSigAPIv2;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @InterfaceName: VideoController视频 及 聊天接口
 * @Description:
 * @Author: lilirui
 * @Date: 2023-04-03
 */
@RestController
@RequestMapping("/video")
public class VideoController {

    @Autowired
    RedisService redisService;

    @Autowired
    MeetingService meetingService;

    @Autowired
    MeetingMapper meetingMapper;
    //    @RequiresPermissions("system:achievement:list")
    @GetMapping("/createroom")
    public AjaxResult createroom(@RequestParam(required = true) String type) {
        Long userid = SecurityUtils.getLoginUser().getUserid();
        TLSSigAPIv2 api = new TLSSigAPIv2(1400801637, "1627109bea381cc197caf4849606631e89d2411a5a4f58623d3a9c71262c9fd6");
        HashMap<String, String> resp = new HashMap<>();
        resp.put("userSig", api.genUserSig(String.valueOf(userid), 180 * 86400));
        String roomId = RandomUtil.getRandomNumString(9);
        resp.put("roomId", roomId);
        ArrayList<Long> userIds = new ArrayList<>();
        userIds.add(userid);
        String key = CacheConstants.MEETING_TYPE_KEY + roomId;
        if (type.equals(WebsocketConstants.DOUBLE_MEETING)) {//双人
            redisService.setCacheObject(key, WebsocketConstants.DOUBLE_MEETING, WebsocketConstants.EXPIRATION_TIME, TimeUnit.MINUTES);
        } else if (type.equals(WebsocketConstants.MULTIPLE_MEETING)) {//多人
            redisService.setCacheObject(key, WebsocketConstants.MULTIPLE_MEETING, WebsocketConstants.EXPIRATION_TIME, TimeUnit.MINUTES);
        }
        return AjaxResult.success(resp);
    }
    @ApiOperation("创建预定会议")
    @PostMapping("createIntendedMeeting")
    public AjaxResult createIntendedMeeting(@RequestBody Meeting meeting) {
        AjaxResult createroom = createroom(WebsocketConstants.MULTIPLE_MEETING);
        Map<String,Object> data = (Map<String, Object>) createroom.get("data");
        String roomId = (String) data.get("roomId");
        String key = CacheConstants.MEETING_TYPE_KEY + roomId;

        Date date = new Date();
        long time = meeting.getEndTime().getTime()-date.getTime() ;
        if (time <0 || meeting.getEndTime().getTime()-meeting.getStartTime().getTime()<0) {
            throw new ServiceException("结束时间非法");
        }
//        if (time <= WebsocketConstants.PREDETERMINE_MEETING_MAX_TIME) {
//            redisService.setCacheObject(key, WebsocketConstants.PREDETERMINE_MEETING, time, TimeUnit.MINUTES);
//        } else {
//            redisService.setCacheObject(key, WebsocketConstants.PREDETERMINE_MEETING, WebsocketConstants.PREDETERMINE_MEETING_MAX_TIME, TimeUnit.MINUTES);
//        }
        redisService.setCacheObject(key, WebsocketConstants.PREDETERMINE_MEETING, time, TimeUnit.MINUTES);

        meeting.changeState();
        meeting.setUserId(SecurityUtils.getUserId());
        meeting.setMeetingCode(roomId);
        meeting.setNickName(SecurityUtils.getLoginUser().getSysUser().getNickName());
        meetingService.save(meeting);
        return createroom;
    }
    @ApiOperation("删除会议")
    @DeleteMapping("IntendedMeeting")
    public AjaxResult DeleteIntendedMeeting(Long id) {
        Meeting byId = meetingService.getById(id);
        boolean b = meetingService.removeById(id);
        redisService.deleteObject(byId.getMeetingCode());
        if (b){
            return AjaxResult.success();
        }
        throw new ServiceException("删除失败");
    }
    @ApiOperation("修改会议")
    @PutMapping("editIntendedMeeting")
    public AjaxResult editIntendedMeeting(@RequestBody Meeting meeting) {
        meetingService.removeById(meeting.getId());
        AjaxResult intendedMeeting = createIntendedMeeting(meeting);
        return intendedMeeting;
    }
    @ApiOperation("我的会议列表")
    @GetMapping("getMyMeeting")
    public AjaxResult getMyMeeting(Integer current, Integer size, Meeting meeting) {
        meeting.setUserId(SecurityUtils.getUserId());
//        return AjaxResult.success(getMeeting(current,size,meeting));
        return getMeeting(current,size,meeting);
    }

    @ApiOperation("会议存在")
    @GetMapping("getMeetingexist")
    public AjaxResult getMeetingexist(String roomId) {

        String key = CacheConstants.MEETING_TYPE_KEY + roomId;
        Object cacheObject = redisService.getCacheObject(key);
        if (cacheObject==null){
            throw new ServiceException("会议不存在");
        }
        return AjaxResult.success();
    }

    @ApiOperation("会议详情")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(meetingService.getById(id));
    }

    @ApiOperation("会议列表")
    @GetMapping("getMeeting")
    public AjaxResult getMeeting(Integer current, Integer size, Meeting meeting) {
        if (Objects.isNull(current)) {
            current = 1;
        }
        if (Objects.isNull(size)) {
            size = 10;
        }
        if (size >= 20) {
            size = 20;
        }
        QueryWrapper<Meeting> queryWrapper = new QueryWrapper<>();
        if (meeting.getUserId()!=null){
            queryWrapper.eq("meeting.user_id", meeting.getUserId());
        }
        if (meeting.getTitle()!=null && !meeting.getTitle().isEmpty()){
            queryWrapper.like("meeting.title", meeting.getTitle());
        }
        if (meeting.getNickName()!=null && !meeting.getNickName().isEmpty()){
            queryWrapper.like("sys_user.nick_name", meeting.getNickName());
        }
        if (meeting.getState()!=null && !meeting.getState().isEmpty()){
            queryWrapper.eq("meeting.state", meeting.getState());
        }
        if (meeting.getMeetingCode()!=null && !meeting.getMeetingCode().isEmpty()){
            queryWrapper.eq("meeting.meeting_code", meeting.getMeetingCode());
        }
        queryWrapper.orderByDesc("meeting.create_time");
        Page<Meeting> page = meetingService.page(new Page<>(current, size), queryWrapper);
        return AjaxResult.success(page);
    }

    @GetMapping("/getUserSig")
    public AjaxResult getUserSig() {
        Long userid = SecurityUtils.getLoginUser().getUserid();
        TLSSigAPIv2 api = new TLSSigAPIv2(1400801637, "1627109bea381cc197caf4849606631e89d2411a5a4f58623d3a9c71262c9fd6");
        HashMap<String, String> resp = new HashMap<>();
        resp.put("userSig", api.genUserSig(String.valueOf(userid), 180 * 86400));
        return AjaxResult.success(resp);
    }

    @InnerAuth
    @GetMapping("/updateState")
    public AjaxResult updateState() {
        meetingService.updateState();
        return AjaxResult.success();
    }
}
